﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using WaterRevenueMS.WebUI.Common;
using System.ComponentModel.Composition;
using WaterRevenueMS.Core.Service.Charge.Impl;
using WaterRevenueMS.WebUI.Extension.Filters;
using WaterRevenueMS.Domain.Common.Models;
using WaterRevenueMS.Domain.ViewModels.Charge.ChargeRecord;
using WaterRevenueMS.Core.Service.Charge;
using WaterRevenueMS.Core.Service.Customer;
using WaterRevenueMS.Componnent.Common;
using WaterRevenueMS.Componnent.Entities.Charge;
using WaterRevenueMS.WebUI.Extension.MvcHelper;
using WaterRevenueMS.Domain.ViewModels.Customer.Customer;
using WaterRevenueMS.Core.Service.BasicSet;
using WaterRevenueMS.Domain.ViewModels.Charge.MeterCharge;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using System.Drawing;
using NPOI.SS.Util;


namespace WaterRevenueMS.WebUI.Controllers
{

    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class MeterChargeController : AdminController
    {
        [Import]
        public IChargeRecordService ChargeRecordService { get; set; }
        [Import]
        private ICustomerService WaterCaliberService { get; set; }


        [AdminLayoutAttribute]
        public ActionResult Index()
        {
            var modell = new MeterChargeModel();
            return View(modell);
        }
        [AdminPermission(PermissionCustomMode.Ignore)]
        public ActionResult List(DataTableParameter param)
        {
            int total = ChargeRecordService.ChargeRecords.Count(t => t.Jiao_FZT == 1);

            var expr = BuildSearchCriteria();

            var filterResult = ChargeRecordService.ChargeRecords.Where(expr).Select(t => new MeterChargeModel
            {
                Id = t.Id,
                Bei_Z = t.Bei_Z,
                CreateDT = t.CreateDT,
                Yong_HYE = t.Customer != null ? t.Customer.Zhang_HYE : 0,
                Ben_QDS = t.Ben_QDS,
                Yong_HZZ= t.Customer != null ? t.Customer.Yong_HZZ :"",
                //     Jiao_FLX = t.Jiao_FLX,
                Shang_QDS = t.Shang_QDS,
                Ben_QYL = t.Ben_QYL,
                He_JYL = t.He_JYL,
                Ben_CJF = t.Ben_CJF,
                UserName = t.Customer != null ? t.Customer.Hu_ZXM : "",
                



            }).OrderBy(t => t.Id).Skip(param.iDisplayStart).Take(param.iDisplayLength).ToList();

            int sortId = param.iDisplayStart + 1;

            var result = from c in filterResult
                         select new[]
                        {
                            c.Id.ToString(),
                             sortId++.ToString(), 
                            c.UserName,  
                            c.Yong_HZZ,
                            c.Yong_HYE.ToString(),
                            
                        c.Ben_QDS.ToString(),
                        c.Shang_QDS.ToString(),
                        c.Ben_QYL.ToString(),
                        c.He_JYL.ToString(),
                        c.Ben_CJF.ToString(),
                        c.CreateDT.ToString(),
                        c.Bei_Z,
                            c.Id.ToString()
                        };

            return Json(new
            {
                sEcho = param.sEcho,
                iDisplayStart = param.iDisplayStart,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }
        [AdminPermission(PermissionCustomMode.Ignore)]
        public string GenerateChargeEXL(string idList)
        {
            string strJson = "{\"state\":\"";
            strJson = strJson + "1\",\"message\":\"成功\"}";
          //  string[] idL = idList.Split(',');
         //   FileStream fs = new FileStream(@idList, FileMode.Open);
            var model = new MeterChargeModel();
            using (FileStream fs = new FileStream(@idList, FileMode.Open))   //打开myxls.xls文件
            {
                HSSFWorkbook wk = new HSSFWorkbook(fs);   //把xls文件中的数据写入wk中
                for (int i = 0; i < wk.NumberOfSheets; i++)  //NumberOfSheets是myxls.xls中总共的表数
                {
                    ISheet sheet = wk.GetSheetAt(i);   //读取当前表数据
                    IRow rowTitle = sheet.GetRow(0);  //读取文件头
                    ICell cellT = rowTitle.GetCell(0);  //
                    if (cellT.ToString() == "流水号" && rowTitle.GetCell(2).ToString() == "用户编号")
                    {
                        for (int j = 1; j <= sheet.LastRowNum; j++)  //LastRowNum 是当前表的总行数
                        {
                            IRow row = sheet.GetRow(j);  //读取当前行数据
                            if (row != null)
                            {
                                ICell cell = row.GetCell(2);  //用户ID
                                if (cell != null)
                                {

                                    model.User_ID = Int32.Parse(cell.ToString());//用户ID
                                    model.Liu_SH = row.GetCell(0).ToString();//流水号
                                    cell = row.GetCell(8); //缴费金额
                                    model.Jiao_FJE = Int32.Parse(cell.ToString());
                                    int intrs = ChargeRecordService.ChangeYE(model);
                                    if (intrs == 1)
                                    {
                                        model.Jiao_FZT = 2;  //更新缴费状态
                                        ChargeRecordService.Update(model);
                                    }
                                }

                            }
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            
           
  
            
            return strJson;
        }
        







        [AdminPermission(PermissionCustomMode.Ignore)]
        public string GenerateRepair(string idList)
        {
            string strJson = "{\"state\":\"";
            strJson = strJson + "1\",\"message\":\"成功\"}";
            string[] idL = idList.Split(',');

            IWorkbook workBook = new HSSFWorkbook();

            ISheet sheet = workBook.CreateSheet("sheet1");

            sheet.SetColumnWidth(1, 50 * 256);  //设置列宽，50个字符宽度。宽度参数为1/256，故乘以256
            /******************写入标题行，合并居中*********************/
          //  IRow row = sheet.CreateRow(0);
          //  ICell cell = row.CreateCell(0);
          //  cell.SetCellValue("用户信息");
          //  ICellStyle style = workBook.CreateCellStyle();
          ////  style.Alignment = ICellStyle.ALIGN_CENTER;
          //  IFont font = workBook.CreateFont();
          //  font.FontHeight = 20 * 20;
          //  style.SetFont(font);
          //  cell.CellStyle = style;
          //  sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 4));
            /******************写入列标题*********************/

            var model = new MeterChargeModel();
            IRow headerRow = sheet.CreateRow(0);
            for (int i = 0; i < model.HeadString.Length; i++)
            {
                headerRow.CreateCell(i).SetCellValue(model.HeadString[i].ToString());
            }
            int rowIndex = 1;
            
            for (Int32 i = 0; i < idL.Length; i++)
            {
                if (idL[i].Trim() != "")
                {
                    Int32 id = Int32.Parse(idL[i].Trim());
                    if ((id != 0))
                    {
   
                        model.Id = id;
                        ChargeRecordService.GetLiuSModel(model);
                        model.Jiao_FZT = 3;
                        ChargeRecordService.Update(model);

                        IRow dataRow = sheet.CreateRow(rowIndex);
                        dataRow.CreateCell(0).SetCellValue(model.Liu_SH);
                        dataRow.CreateCell(1).SetCellValue(model.Yong_HZZ);
                        dataRow.CreateCell(2).SetCellValue(model.User_ID);
                        dataRow.CreateCell(3).SetCellValue(model.UserName);
                        dataRow.CreateCell(4).SetCellValue(model.Ben_QDS);
                        dataRow.CreateCell(5).SetCellValue(model.Ben_QYL);
                        dataRow.CreateCell(6).SetCellValue(model.Ben_CJF);
                        dataRow.CreateCell(7).SetCellValue(model.Yong_HYE.ToString());
                        
                    
                        rowIndex++; 
                    }
                        
                }
                     

            }
            FileStream file = new FileStream(@"D:\demo.xls", FileMode.Create);
            workBook.Write(file);
            file.Close();


            return strJson;
        }


        public ActionResult Create()
        {
            var model = new MeterChargeModel();

            return PartialView(model);
        }

        public ActionResult Edit(int Id)
        {
            var model = new MeterChargeModel();
            var entity = ChargeRecordService.ChargeRecords.FirstOrDefault(t => t.Id == Id);
            if (null != entity)
            {
                model = new MeterChargeModel
                {
                    Bei_Z = entity.Bei_Z,
                    Id = entity.Id,
                    Jiao_FJE = entity.Jiao_FJE
                };

                model.UserName = entity.Customer.Hu_ZXM;

                model.User_ID = (int)entity.User_Id;

            }
            return PartialView(model);
        }
        [HttpPost]
        public ActionResult Edit(MeterChargeModel model)
        {

            return PartialView(model);
   
        }



        private Expression<Func<ChargeRecord, Boolean>> BuildSearchCriteria()
        {
            DynamicLambda<ChargeRecord> bulider = new DynamicLambda<ChargeRecord>();
            Expression<Func<ChargeRecord, Boolean>> expr = null;
            if (!string.IsNullOrEmpty(Request["UserName"]))
            {
                var data = Request["UserName"].Trim();
                Expression<Func<ChargeRecord, Boolean>> tmp = t => t.Customer.Hu_ZXM.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }


            Expression<Func<ChargeRecord, Boolean>> tmpSolid = t => t.Jiao_FZT == 1;
            expr = bulider.BuildQueryAnd(expr, tmpSolid);

            return expr;
        }


    }

}







